# -*- coding: utf-8 -*-
"""
Created on Thu Jul 10 18:39:33 2025

@author: DELL
"""

import os
import cinrad
import numpy as np


# 主文件夹和目标文件夹路径
source_folder = r"E:/AI-data/CS"
destination_folder = r"E:/AI-data/output"

# 创建目标文件夹，如果不存在
os.makedirs(destination_folder, exist_ok=True)

# 遍历所有子文件夹和文件
for root, dirs, files in os.walk(source_folder):
    for file in files:
        if file.endswith(".bz2"):
            # 构造文件路径
            file_path = os.path.join(root, file)
            
            # 读取数据
            f= cinrad.io.read_auto(file_path)

            #提取dbz计算CR，resolution(tuple):为分辨率。
            r_list = list(f.iter_tilt(230, 'REF'))
            ff = cinrad.calc.quick_cr(r_list, resolution=(1000,1000)) 
            data = ff.CR
            
            # 获取相应的子文件夹路径
            relative_path = os.path.relpath(root, source_folder)
            output_folder = os.path.join(destination_folder, relative_path)

            # 创建与源文件夹结构相同的目标子文件夹
            os.makedirs(output_folder, exist_ok=True)

            # 保存，文件名与 bz2 文件名相同
            output_file_path = os.path.join(output_folder, file.replace('.bz2', '.npz'))
            
            np.savez_compressed(output_file_path, 
                                CR = data.values, 
                                lon = data.coords['longitude'].values,
                                lat = data.coords['latitude'].values)


            print(f"Processed and saved : {output_file_path}")
            
            
            
            
            
            
            
            
            
            
            